package win.somereason.test.baseline_web.common;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import win.somereason.test.baseline_web.entity.SecUserDetails;

/**
 * Created by Qingsheng.Sun on 2018/4/2.
 */
public class AuthHelper {
    /**
     * 获取登录用户的信息,也就是UserDetailsService.loadUserByUsername中返回的类.
     * 如果没有设置UserDetailsService,默认的用户信息类是org.springframework.security.core.userdetails.User
     * @return
     */
    public static SecUserDetails getCurrentUser() {
        Object userDetails = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userDetails instanceof SecUserDetails) {
            return ((SecUserDetails) userDetails);
        } else if (userDetails instanceof User) {// 使用程序内置用户名密码登录.
            SecUserDetails secUserDetails = new SecUserDetails();
            secUserDetails.setAccountNonExpired(((User) userDetails).isAccountNonExpired());
            secUserDetails.setAccountNonLocked(((User) userDetails).isAccountNonLocked());
            secUserDetails.setCredentialsNonExpired(((User) userDetails).isCredentialsNonExpired());
            secUserDetails.setUserId(-1);
            secUserDetails.setEnabled(((User) userDetails).isEnabled());
            secUserDetails.setUsername(((User) userDetails).getUsername());
            secUserDetails.setPassword(((User) userDetails).getPassword());
            return secUserDetails;
        }
        return null;
    }
}
